package com.sq.partner.manager.controller;

import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.service.DictManagerService;
import com.sq.partner.manager.service.SchoolConfigService;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;
/**
 *  学校信息配置
 */
@Controller
@RequestMapping("/schoolConfiger")
public class SchoolConfigController {
	private static Logger logger = LogUtil.getLog(SchoolConfigController.class);
	
	@Resource
	private SchoolConfigService schoolConfigService;
	@Resource
	private DictManagerService dictManagerService;
	
	@RequestMapping(value = "/list")
	public String list() throws Exception {
		logger.debug("forward newLifeCoreProduct successful....");
			return "facadeManage/schoolConfiger/list";
	}
	
	@RequestMapping(value = "/querySchoolConfig")
	@ResponseBody
	public Page<DictDto> querySchoolConfig(DictDto dictDto,Page<DictDto> page) throws Exception{
		List<DictDto> list = new ArrayList<DictDto>();
		Map<String, Object> map=new HashMap<String, Object>();
		if( dictDto!=null){
			if(StrUtil.isNotEmpty(dictDto.getCode())){
				map.put("code", dictDto.getCode());
			}else{
				map.put("code", "");
			}
			if(StrUtil.isNotEmpty(dictDto.getCodeDesc())){
				map.put("codeDesc", "%"+dictDto.getCodeDesc()+"%");
			}
		}
		map.put("codeType", "school_config");
		map.put("BEGINROW", (page.getCurrent()-1) * 10 );
		map.put("ENDROW", page.getCurrent() * 10);
		page.setMap(map);
		page=dictManagerService.querySchoolConfigList(page);
		List<DictDto> data = page.getData();
		for (DictDto dto : data) {
			dto.setOldCode(dto.getCode().substring(0, 8));
			dto.setInsertDate(dto.getInsertDate().substring(0, 19));
		}
		
		return page;
		
	}
	
	/**
	 * 查询学校信息下拉
	 */
	@RequestMapping(value = "/querySchoolConfigSelect")
	public @ResponseBody List<Map<String, Object>> querySchoolConfigSelect(String flag,String code,String parentCode,HttpSession session) throws Exception{
		Map<String,Object> paramMap = new HashMap<String, Object>();
		paramMap.put("parentCode", parentCode);
		paramMap.put("code", code);
		List<Map<String, Object>> list = schoolConfigService.querySchoolConfigSelect(paramMap);
		return list;
	}
	
	@RequestMapping("/demandExportExcel")
	@ResponseBody
	public void exportCardExcel(HttpSession session,HttpServletResponse response, HttpServletResponse resp,DictDto dictDto) throws Exception {
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		Map<String, Object> paramMap=new HashMap<String,Object>();
		if (dictDto.getCode()!=null) {
			paramMap.put("code", dictDto.getCode());
		}else{
			paramMap.put("code", "");
		}
		paramMap.put("codeDesc", dictDto.getCodeDesc());
		paramMap.put("codeType", "school_config");
		List<Map<String, Object>> demandExportList = schoolConfigService.demandExportSelect(paramMap);
		for (Map<String, Object> map : demandExportList) {
			map.put("CODE", map.get("CODE").toString().substring(0, 8));
			if (map.get("OTHER_CODE2").toString().contains(",")) {
				String[] arr = map.get("OTHER_CODE2").toString().split(",");
				for (int i = 0; i < arr.length; i++) {
					if (i==0) {
						map.put("OTHER_CODE2", arr[0]);
					}else {
						Map<String, Object> newMap = new HashMap<String, Object>();
						newMap.put("CODE", map.get("CODE"));
						newMap.put("CODE_NAME", map.get("CODE_NAME"));
						newMap.put("CODE_DESC", map.get("CODE_DESC"));
						newMap.put("OTHER_CODE", map.get("OTHER_CODE"));
						newMap.put("OTHER_CODE2", arr[i]);
						list.add(newMap);
					}
				}
			}
		}
		demandExportList.addAll(list);
		sortMap(demandExportList);
        schoolConfigService.downloadSchoolConfigFile1(demandExportList, response);
	}
	/**
	 * excel上传
	 */
	@RequestMapping(value = "/schoolConfigExcelImport")
	public void addNlifeCoreProdFile(@RequestParam MultipartFile[] myfiles,HttpServletResponse response, HttpSession session) throws Exception {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		List<InputStream> inputStreams = null;
		Page<String>  page = new Page<String>();
		// 上传文件的原名(即上传前的文件名字)
		try {
			out = response.getWriter();
			if (myfiles.length < 1) {
				page.setResult("error");
				page.setMessage("请添加上传文件!");
			}else{
				GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
				inputStreams=schoolConfigService.getFileInputStream(myfiles);
				schoolConfigService.insertDataToDB(inputStreams.get(0),user,session);
				logger.info("读写成功");
				page.setResult("success");
				page.setMessage((String)session.getAttribute("result"));
			}
		} catch (Exception e) {
			logger.info("---------学校信息配置Excel导入失败",e);
			page.setResult("error");
			page.setMessage(e.getMessage());
		} finally {
			if(null!=inputStreams){
				for (InputStream input:inputStreams){
					try{
						input.close();
					}catch(Exception e){
						logger.warn("关闭流失败！", e);
					}
				}
			}
			if (null!=out) {
				out.write(JsonUtils.toJson(page));
				try {
					out.close();
				} catch (Exception e) {
					logger.warn("关闭流失败！", e);
				}
			}
		}
	}
	
	@RequestMapping(value = "/updateSchoolConfig")
	@ResponseBody
	public Page<DictDto> updateSchoolConfig(String code,String schoolName,String schoolDesc,String gradeName,String className) throws Exception{
		Page<DictDto> page = new Page<DictDto>();
		Map<String, Object> schoolMap = new HashMap<String, Object>();
		Map<String, Object> gradeMap = new HashMap<String, Object>();
		String schoolCode = code.substring(0, 9);
		gradeMap.put("code", code);
		schoolMap.put("code", schoolCode);
		List<Map<String, Object>> schoolConfig = schoolConfigService.querySchoolConfigSelect(schoolMap);
		List<Map<String, Object>> gradeConfig = schoolConfigService.querySchoolConfigSelect(gradeMap);
		DictDto schoolDict = new DictDto();
		DictDto gradeDict = new DictDto();
		schoolDict.setCode(schoolConfig.get(0).get("CODE").toString());
		schoolDict.setCodeType(schoolConfig.get(0).get("CODE_TYPE").toString());
		schoolDict.setCodeName(schoolName);
		schoolDict.setCodeDesc(schoolDesc);
		
		gradeDict.setCode(gradeConfig.get(0).get("CODE").toString());
		gradeDict.setCodeType(gradeConfig.get(0).get("CODE_TYPE").toString());
		gradeDict.setCodeName(gradeName);
		gradeDict.setCodeDesc(className);
		schoolConfigService.updateSchoolConfig(schoolDict);
		schoolConfigService.updateSchoolConfig(gradeDict);
		page.setMessage("更新成功");
		return page;
	}
	
	@RequestMapping(value = "/delSchoolConfig")
	@ResponseBody
	public Page<DictDto> delSchoolConfig(String code) throws Exception{
		Page<DictDto> page = new Page<DictDto>();
		Map<String, Object> gradeMap = new HashMap<String, Object>();
		gradeMap.put("parentCode", code.substring(0,9));
		List<Map<String, Object>> gradeConfig = schoolConfigService.querySchoolConfigSelect(gradeMap);
		if (gradeConfig.size()==1) {
			DictDto schoolDict = new DictDto();
			schoolDict.setCode(code.substring(0,9));
			schoolDict.setCodeType("school_config");
			dictManagerService.deleteGatewayDict(schoolDict);
		}
		DictDto dict = new DictDto();
		dict.setCode(code);
		dict.setCodeType("school_config");
		dictManagerService.deleteGatewayDict(dict);
		page.setMessage("删除成功");
		DictCache.refreshCache();
		return page;
	}
	
	
	
	 private static void sort(List<DictDto> data) {
		 
	        Collections.sort(data, new Comparator<DictDto>() {
	 
				@Override
				public int compare(DictDto d1, DictDto d2) {
					Integer a = Integer.parseInt(d1.getOldCode());
	                Integer b = Integer.parseInt(d2.getOldCode());
	                // 升序
	                return a.compareTo(b);
				}
	        });
	    }
	 
	 private static void sortMap(List<Map<String, Object>> data) {
		 
	        Collections.sort(data, new Comparator<Map<String, Object>>() {
	 
				@Override
				public int compare(Map<String, Object> o1,
						Map<String, Object> o2) {
					Integer a = Integer.parseInt((String) o1.get("CODE"));
	                Integer b = Integer.parseInt((String) o2.get("CODE"));
	                // 升序
	                return a.compareTo(b);
				}
	        });
	    }
}
